//
//  KAMineVC.swift
//  kano
//
//  Created by Sophia on 2024/8/19.
//


import UIKit
import Flutter
import StoreKit

class KAMineVC: KABaseVC{
    
    lazy var var_scrollView: UIScrollView = {
        let var_scrollView = UIScrollView(frame: CGRectMake(0, 0, view.width, UIDevice.ka_noNavHeight))
        var_scrollView.backgroundColor = .colorFFF
        var_scrollView.isScrollEnabled = true
//        var_scrollView.contentSize = CGSize(width: var_screenWidth, height: var_screenHeight)
        var_scrollView.bounces = true
        var_scrollView.delegate = self
        return var_scrollView
    }()
    
    lazy var var_bgView: UIImageView = {
        let var_bgView = UIImageView(frame: CGRectMake(0, 0, var_screenWidth, kscale(235)))
        var_bgView.image = UIImage(named: "home_header")
        return var_bgView
    }()
    lazy var var_titleLabel: UILabel = {
        let var_titleLabel = UILabel()
        var_titleLabel.x = kscale(16)
        var_titleLabel.y = UIDevice.ka_statusBarHeight + kscale(18)
        var_titleLabel.width = var_screenWidth-kscale(32)
        var_titleLabel.height = kscale(23)
        var_titleLabel.font = UIFont.systemFont(ofSize: kscale(18), weight: .bold)
        var_titleLabel.textColor = .color323135
        var_titleLabel.text = "Mine"
        return var_titleLabel
    }()

    lazy var var_contentView: UIView = {
        let var_contentView = UIView()
        let y = UIDevice.ka_statusBarHeight+kscale(87)
        var_contentView.frame = CGRectMake(0, y,var_screenWidth, UIDevice.ka_noNavHeight-y)
        var_contentView.backgroundColor = .white
        let maskPath = UIBezierPath(roundedRect: var_contentView.bounds,
                                    byRoundingCorners: [.topLeft, .topRight],
                                    cornerRadii: CGSize(width: 24, height: 24))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = var_contentView.bounds
        maskLayer.path = maskPath.cgPath
        var_contentView.layer.mask = maskLayer
        return var_contentView
    }()
    static let var_itemCellId = "KAMineCell"
    lazy var var_tableView: UITableView = {
        let var_tableView = UITableView()
        var_tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        var_tableView.backgroundColor = .colorFFF
        var_tableView.frame = CGRect(x: 0.0, y: 0.0, width: view.width, height: var_contentView.height)
        var_tableView.register(KAMineCell.self, forCellReuseIdentifier: Self.var_itemCellId)
        var_tableView.dataSource = self
        var_tableView.delegate = self
        var_tableView.separatorStyle = .none
        var_tableView.separatorInset = .zero
        var_tableView.separatorInsetReference = .fromCellEdges
        var_tableView.tableHeaderView = var_headerView
        //var_tableView.separatorColor = UIColor(0xffffff, alphaVaule: 0.15)
        return var_tableView
    }()
    lazy var var_headerView: KAMineHeader = {
        let var_headerView = KAMineHeader()
        let var_tap = UITapGestureRecognizer(target: self, action: #selector(tapClick(_ :)))
        var_headerView.var_cornerView.addGestureRecognizer(var_tap)
        
        let banktap = UITapGestureRecognizer(target: self, action: #selector(tobank))
        var_headerView.var_bankAccView.addGestureRecognizer(banktap)
        
        return var_headerView
    }()
    lazy var var_dataArray = [KARowInfo]()
    
    @objc func tapClick(_ sender: UITapGestureRecognizer) {
        navigationController?.pushViewController(KABillListVC(), animated: true)
    }
    
    @objc func tobank() {
        guard let json = KADBDBManager.ka_getObject(by: "auditStatus") as? String  else {return}
        let auditState = json.kj.model(KAAuditState.self)
        if auditState?.auditCondition != 1 {
            let message = "Please Apply for Credit First, Then Add Bank Account"
            let alert = KAAlertView.alert(withTitle: "Tips", subtitle: message) { _ in
            }
            alert.addAction(KAAlertAction(title: "I known", titleColor: .blue, backgroundColor: .clear) { action in
            })
            alert.show()
        } else {
            KAFlutterManager.showFlutterVC(route: "/banklist", parameter: ["mobile" : KAUserManager.shared.user.notificationMessage])
        }
    }
    
    var basicModel: KABasicInfoModel?

}
extension KAMineVC {
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestBaseInfo()
//        rateApp()
    }
    //评分
    func rateApp() {
        // 检查是否支持评分功能
        if #available(iOS 10.3, *) {
            // 在iOS 10.3及以上版本使用SKStoreReviewController
            SKStoreReviewController.requestReview()
        } else {
            // 在iOS 10.3以下版本没有公开的API，可以选择跳转到App Store评分页面
            let var_appid = Bundle.main.bundleIdentifier
            if let url = URL(string: "https://itunes.apple.com/app/\(var_appid)") {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
    func requestBaseInfo() {
        let paraDic: [String : Any] = [
            "softwareUpdateVersions": KAUserManager.shared.user.softwareUpdateVersions,
        ]
        view.showLoading()
        billProvider.request(.userBasic(paraDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KABasicInfoModel>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let model = response?.voucherQuantity else { return }
                            basicModel = model
                            var_tableView.reloadData()

                            var_headerView.var_limitView.var_cashLabel.text = "₦" + model.loanInterestPercentage.separatorString()
                            var_headerView.var_bankAccView.var_cashLabel.text = model.userCategoryType.separatorString()
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ka_configData()
        ka_setUI()
    }
    func ka_configData() {
        let msg = KARowInfo(icon: "mine_msg", title: "Message Center", isFirst: true, isLast: false, type: .msgCenter)

        let security = KARowInfo(icon: "mine_security", title: "Account security", isFirst: true, isLast: false, type: .accSecurity)
        let coupon = KARowInfo(icon: "mine_coupon", title: "Coupon", isFirst: false, isLast: false, type: .coupon)

        let privacy = KARowInfo(icon: "mine_terms", title: "Privacy Policy", isFirst: false, isLast: false, type: .privacy)
        let terms = KARowInfo(icon: "mine_terms", title: "Loan Terms", isFirst: false, isLast: false, type: .loanTerms)

        let help = KARowInfo(icon: "mine_question", title: "Help Center", isFirst: false, isLast: true, type: .helpCenter)

//        var_dataArray.append(msg)
        var_dataArray.append(security)
        var_dataArray.append(coupon)
        var_dataArray.append(privacy)
        var_dataArray.append(terms)
        var_dataArray.append(help)
    }
    func ka_setUI() {
        view.backgroundColor = .white
        view.addSubview(var_scrollView)
        var_scrollView.addSubview(var_bgView)
        var_scrollView.addSubview(var_contentView)
        var_bgView.addSubview(var_titleLabel)
        var_contentView.addSubview(var_tableView)
    }
}

extension KAMineVC : UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var_dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let var_cell: KAMineCell = KAMineCell.ka_cell(for: tableView)
        let rowData = var_dataArray[indexPath.row]
        var_cell.var_titleLabel.text = rowData.title
        var_cell.var_cellImg.image = UIImage(named: rowData.icon)
        
        var_cell.var_countLabel.isHidden = true
        if rowData.type == .coupon {
            var_cell.var_countLabel.isHidden = false
            var_cell.var_countLabel.text = "\(basicModel?.existingUserIdentifier ?? 0)"
        }
        
        if (rowData.isFirst && rowData.isLast) {
            var_cell.var_cornerView.ka_addCorner(withRadius: kscale(10))
        } else {
            if (rowData.isFirst) {
                var_cell.var_cornerView.ka_addTopCorner(withRadius: kscale(10))
            }
            if (rowData.isLast) {
                var_cell.var_cornerView.ka_addBottomCorner(withRadius: kscale(10))
            }
        }
        return var_cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return kscale(50.0)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let rowData = var_dataArray[indexPath.row]
        
        switch rowData.type {
        case .msgCenter: break
           
        case .accSecurity:
            navigationController?.pushViewController(KASecurityVC(), animated: true)

//            let vc = KAAdvanceFail(model: KAApply(), basic: KABasic())
//            navigationController?.pushViewController(vc, animated: true)
        case .coupon:
            KAFlutterManager.showFlutterVC(route: "/voucherList", parameter: ["mobile" : KAUserManager.shared.user.notificationMessage])
        case .privacy:
//            if let filePath = Bundle.main.path(forResource: "privacy", ofType: "html") {
//                let fileURL = URL(fileURLWithPath: filePath)
//                let webVC = KAWebVC.init(title: "Privacy Policy", url: fileURL)
//                self.navigationController?.pushViewController(webVC, animated: true)
//            }
            self.navigationController?.pushViewController(KAPrivacyAgreement(), animated: true)
        case .loanTerms:
            if let filePath = Bundle.main.path(forResource: "loanTerms", ofType: "html") {
                let fileURL = URL(fileURLWithPath: filePath)
                let webVC = KAWebVC.init(title: "Loan Terms", url: fileURL)
                self.navigationController?.pushViewController(webVC, animated: true)
            }
        case .helpCenter:
            KAFlutterManager.showFlutterVC(route: "/helpCenter", parameter: [:])
            
//            let titleStr = "Your BVN number has been used by phone number \("96755212135464")"
//            let subStr = "Please log in with your original phone number or contact customer service for consultation."
//            let alertView = KAApplyIdAlert(title: titleStr, subTitle: subStr)
//            alertView.ka_show()
            
//            UIViewController.ka_current().navigationController?.pushViewController(KAApplyResultVC(reviewResult: .fail), animated: true)

        default: break
            
        }
    }
}
